<?php

namespace App\Http\Controllers\Supervisor;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use App\Supervisor;
use App\Thesis;
use App\Student;
use App\Comment;
use \PhpOffice\PhpWord\TemplateProcessor;
use App\Description;
use App\Proposal;
use App\Paper;
use App\SupervisorComment;
use App\ReviewerComment;
use App\DefenseComment;

use Storage;

class ThesisController extends Controller
{

    public function edit_title() {

        $user = \Auth::user();
        $supervisor = $user->supervisor;
        $approvedStudents = $supervisor->students()->wherePivot("isApproved", true)->get();
        return view('supervisor.thesistitle', compact("approvedStudents", "user"));
    }

    public function check_title(Request $request, $student_id) {
        $student = Student::find($student_id);
        $user = \Auth::user();
        $current = $student->title()->where('current', '>', 0)->first();
        $history = $student->title()->orderBy('created_at', 'desc')->get();
        $edit = false;
        $thesis = $student->thesis;
        if ($thesis == null) {
            $thesis = new Thesis;
            $thesis->student_id = $student->id; 
            $thesis->description = "";
            $thesis->proposal = "";
            $thesis->paper = "";
            $thesis->save();;
        } 
        $commentInfo = array("head"=>"和学生讨论选题", "type" => 1001, "student_id"=> $student->id);
        $comments = Comment::where('student_id', $student->id)->where(function ($query) {
            $query->where('type', 1)->orWhere('type', 1001);
        })->get();
        return view('supervisor.check_title', compact("thesis", "current", "user", "edit", "history", "commentInfo", "comments", "student"));

    }

    public function store_title(Request $request)
    {
        
        $thesis = Student::find($request->input('student'))->thesis;
        $thesis->approved = true;
        $thesis->save();

        return Redirect::to('supervisor/thesis/edittitle');
    }

    public function listdescription() {

        $user = \Auth::user();
        $supervisor = $user->supervisor;
        $approvedStudents = $supervisor->students()->wherePivot("isApproved", true)->get();
        return view('supervisor.thesisdescription', compact("approvedStudents", "user"));
    }

    public function check_description(Request $request, $student_id) {
        $student = Student::find($request->student_id);
        $user = \Auth::user();
        $current = $student->description()->where('current', '>', 0)->first();
        $history = $student->description()->orderBy('created_at', 'desc')->get();
        $edit = false;
        $thesis = $student->thesis;
        if ($thesis == null) {
            $thesis = new Thesis;
            $thesis->student_id = $student->id; 
            $thesis->description = "";
            $thesis->proposal = "";
            $thesis->paper = "";
            $thesis->save();;
        } 
        $commentInfo = array("head"=>"和学生讨论任务书", "type" => 1002, "student_id"=> $student->id);
        $comments = Comment::where('student_id', $student->id)->where(function ($query) {
            $query->where('type', 2)->orWhere('type', 1002);
        })->get();
        return view('supervisor.check_description', compact("current", "thesis", "user", "edit", "history", "commentInfo", "comments", "student"));

    }

    public function store_description(Request $request)
    {
        
        $thesis = Student::find($request->input('student'))->thesis;
        $thesis->description_approved = true;
        $thesis->save();

        $user = \Auth::user();
        $supervisor = $user->supervisor;
        $approvedStudents = $supervisor->students()->wherePivot("isApproved", true)->get();
        return view('supervisor.thesisdescription', compact("approvedStudents", "user"));
    }

    public function store_descriptionfile(Request $request)
    {
        $this->validate($request, [
        'description' => 'required|min:4',
        'comment' => 'required|min:2',
        ]);
        $student = Student::find($request->input('student_id'));
        $user = $student->user;
        $thesis = $student->thesis;

        $count = $student->description->count();
        $file = $request->file('description');

        // 文件是否上传成功
        if ($file->isValid()) {

            // 获取文件相关信息
            $ext = $file->getClientOriginalExtension();     // 扩展名
            $realPath = $file->getRealPath();   //临时文件的绝对路径
            // 上传文件
            $filename = "任务书_" . $user->username . "_" . $user->name . '_'. $count . '.' . $ext;
            // 使用我们新建的uploads本地存储空间（目录）
            if ($thesis->description != null) {
                Storage::disk('descriptions')->delete($thesis->description);
            }
            $bool = Storage::disk('descriptions')->put($filename, file_get_contents($realPath));
            if ($bool) {
                $student->description()->update(['current'=>0]);
                $description = new Description;
                $description->student_id = $student->id;
                $description->description = $filename;
                $description->comment= $request->input('comment');
                $description->current = 1;
                $description->by_supervisor = 1;

                $description->save();
            }

        }
        return redirect()->back()->withInput()->withErrors('提交成功！');
    }

    public function listproposal() {

        $user = \Auth::user();
        $supervisor = $user->supervisor;
        $approvedStudents = $supervisor->students()->wherePivot("isApproved", true)->get();
        return view('supervisor.thesisproposal', compact("approvedStudents", "user"));
    }

    public function check_proposal(Request $request, $student_id) {
        $student = Student::find($request->student_id);
        $user = \Auth::user();
        $current = $student->proposal()->where('current', '>', 0)->first();
        $history = $student->proposal()->orderBy('created_at', 'desc')->get();
        $edit = false;
        $thesis = $student->thesis;
        if ($thesis == null) {
            $thesis = new Thesis;
            $thesis->student_id = $student->id; 
            $thesis->description = "";
            $thesis->proposal = "";
            $thesis->paper = "";
            $thesis->save();
        } 
        $commentInfo = array("head"=>"和学生讨论任务书", "type" => 1003, "student_id"=> $student->id);
        $comments = Comment::where('student_id', $student->id)->where(function ($query) {
            $query->where('type', 3)->orWhere('type', 1003);
        })->get();
        return view('supervisor.check_proposal', compact("current", "thesis", "user", "edit", "history", "commentInfo", "comments", "student"));

    }


    public function store_proposal(Request $request)
    {
        
        $thesis = Student::find($request->input('student'))->thesis;
        $thesis->proposal_approved = true;
        $thesis->save();

        $user = \Auth::user();
        $supervisor = $user->supervisor;
        $approvedStudents = $supervisor->students()->wherePivot("isApproved", true)->get();
        return view('supervisor.thesisproposal', compact("approvedStudents", "user"));
    }


    public function store_proposalfile(Request $request)
    {
        $this->validate($request, [
        'proposal' => 'required|min:4',
        'comment' => 'required|min:2',
        ]);
        $student = Student::find($request->input('student_id'));
        $user = $student->user;
        $thesis = $student->thesis;

        $count = $student->proposal->count();
        $file = $request->file('proposal');

        // 文件是否上传成功
        if ($file->isValid()) {

            // 获取文件相关信息
            $ext = $file->getClientOriginalExtension();     // 扩展名
            $realPath = $file->getRealPath();   //临时文件的绝对路径
            // 上传文件
            $filename = "开题报告_" . $user->username . "_" . $user->name . '_'. $count . '.' . $ext;
            // 使用我们新建的uploads本地存储空间（目录）
            if ($thesis->proposal != null) {
                Storage::disk('proposals')->delete($thesis->proposal);
            }
            $bool = Storage::disk('proposals')->put($filename, file_get_contents($realPath));
            if ($bool) {
                $student->proposal()->update(['current'=>0]);
                $proposal = new Proposal;
                $proposal->student_id = $student->id;
                $proposal->proposal = $filename;
                $proposal->comment= $request->input('comment');
                $proposal->current = 1;
                $proposal->by_supervisor = 1;

                $proposal->save();
            }

        }
        return redirect()->back()->withInput()->withErrors('提交成功！');
    }

    public function listpaper() {

        $user = \Auth::user();
        $supervisor = $user->supervisor;
        $approvedStudents = $supervisor->students()->wherePivot("isApproved", true)->get();
        return view('supervisor.thesispaper', compact("approvedStudents", "user"));
    }

    public function check_paper(Request $request, $student_id) {
        $student = Student::find($request->student_id);
        $user = \Auth::user();
        $current = $student->paper()->where('current', '>', 0)->first();
        $history = $student->paper()->orderBy('created_at', 'desc')->get();
        $edit = false;
        $thesis = $student->thesis;
        if ($thesis == null) {
            $thesis = new Thesis;
            $thesis->student_id = $student->id; 
            $thesis->description = "";
            $thesis->proposal = "";
            $thesis->paper = "";
            $thesis->save();
        } 
        $commentInfo = array("head"=>"和学生讨论论文", "type" => 1004, "student_id"=> $student->id);
        $comments = Comment::where('student_id', $student->id)->where(function ($query) {
            $query->where('type', 4)->orWhere('type', 1004);
        })->get();
        return view('supervisor.check_paper', compact("current", "thesis", "user", "edit", "history", "commentInfo", "comments", "student"));

    }

    public function store_paper(Request $request)
    {
        
        $thesis = Student::find($request->input('student'))->thesis;
        $thesis->paper_approved = true;
        $thesis->save();

        $user = \Auth::user();
        $supervisor = $user->supervisor;
        $approvedStudents = $supervisor->students()->wherePivot("isApproved", true)->get();
        return view('supervisor.thesispaper', compact("approvedStudents", "user"));
    }

    public function store_paperfile(Request $request)
    {
        $this->validate($request, [
        'paper' => 'required|min:4',
        'comment' => 'required|min:2',
        ]);
        $student = Student::find($request->input('student_id'));
        $user = $student->user;
        $thesis = $student->thesis;

        $count = $student->paper->count();
        $file = $request->file('paper');

        // 文件是否上传成功
        if ($file->isValid()) {

            // 获取文件相关信息
            $ext = $file->getClientOriginalExtension();     // 扩展名
            $realPath = $file->getRealPath();   //临时文件的绝对路径
            // 上传文件
            $filename = "论文_" . $user->username . "_" . $user->name . '_'. $count . '.' . $ext;
            // 使用我们新建的uploads本地存储空间（目录）
            if ($thesis->paper != null) {
                Storage::disk('papers')->delete($thesis->paper);
            }
            $bool = Storage::disk('papers')->put($filename, file_get_contents($realPath));
            if ($bool) {
                $student->paper()->update(['current'=>0]);
                $paper = new Paper;
                $paper->student_id = $student->id;
                $paper->paper = $filename;
                $paper->comment= $request->input('comment');
                $paper->current = 1;
                $paper->by_supervisor = 1;

                $paper->save();
            }

        }
        return redirect()->back()->withInput()->withErrors('提交成功！');
    }


    public function list_supervise_comment() {

        $user = \Auth::user();
        $supervisor = $user->supervisor;
        $students = $supervisor->students()->wherePivot("isApproved", true)->get();
        $title = "指导老师评阅意见";
        $action = "supervise";
        return view('supervisor.list_supervise_comment', compact("students", "user", "title", "action"));
    }

    public function supervise_comment(Request $request, $student_id) {
        $student = Student::find($request->student_id);
        $user = \Auth::user();
        $history = $student->paper()->orderBy('created_at', 'desc')->get();

        $title = "学生论文最终评语及成绩";
        $action = "supervise_comment";
        $who = "指导老师意见";
        return view('supervisor.common_comment', compact("user", "history", "student", "title", "action", "who"));      
    }

    public function supervise_comment_store(Request $request) {
        $student = Student::find($request->student);
        $user = \Auth::user();
        $supervisor = $user->supervisor;
        $supervise_comment = $student->supervise_comment;
        if ($supervise_comment == null) {
            $supervise_comment = new SupervisorComment;
           
        } 
        $supervise_comment->student_id = $student->id; 
        $supervise_comment->supervisor_id = $supervisor->id;
        $supervise_comment->content = $request->content;
        $supervise_comment->grade = $request->grade;
        $supervise_comment->save();
        return redirect()->back()->withInput()->withErrors('提交成功！');
    }

    public function list_review_comment() {
        $user = \Auth::user();
        $supervisor = $user->supervisor;
        $students = $supervisor->review_students()->get();
        $title = "评阅老师意见";
        $action = "review";
        return view('supervisor.list_review_comment', compact("students", "user", "title", "action"));

    }

    public function review_comment(Request $request, $student_id) {
        $student = Student::find($request->student_id);
        $user = \Auth::user();
        $history = $student->paper()->orderBy('created_at', 'desc')->get();

        $title = "学生论文最终评语及成绩";
        $action = "review_comment";
        $who = "评阅老师意见";
        return view('supervisor.common_comment', compact("user", "history", "student", "title", "action", "who"));      
    }

    public function review_comment_store(Request $request) {
        $student = Student::find($request->student);
        $user = \Auth::user();
        $supervisor = $user->supervisor;
        $review_comment = $student->review_comment;
        if ($review_comment == null) {
            $review_comment = new ReviewerComment;
           
        } 
        $review_comment->student_id = $student->id; 
        $review_comment->supervisor_id = $supervisor->id;
        $review_comment->content = $request->content;
        $review_comment->grade = $request->grade;
        $review_comment->save();
        return redirect()->back()->withInput()->withErrors('提交成功！');
    }


    public function list_defense_comment() {
        $user = \Auth::user();
        $supervisor = $user->supervisor;
        $students = $supervisor->defense_students()->get();
        $title = "答辩老师意见";
        $action = "defense";
        return view('supervisor.list_defense_comment', compact("students", "user", "title", "action"));

    }

    public function defense_comment(Request $request, $student_id) {
        $student = Student::find($request->student_id);
        $user = \Auth::user();
        $history = $student->paper()->orderBy('created_at', 'desc')->get();

        $title = "学生论文答辩评语及成绩";
        $action = "defense_comment";
        $who = "答辩老师意见";
        return view('supervisor.common_comment', compact("user", "history", "student", "title", "action", "who"));      
    }

    public function defense_comment_store(Request $request) {
        $student = Student::find($request->student);
        $user = \Auth::user();
        $supervisor = $user->supervisor;
        $defense_comment = $student->defense_comment;
        if ($defense_comment == null) {
            $defense_comment = new DefenseComment;
           
        } 
        $defense_comment->student_id = $student->id; 
        $defense_comment->supervisor_id = $supervisor->id;
        $defense_comment->content = $request->content;
        $defense_comment->grade = $request->grade;
        $defense_comment->save();
        return redirect()->back()->withInput()->withErrors('提交成功！');
    }


    public function edit_review($student_id)
    {
        $user = \Auth::user();
        $student = Student::find($student_id);
        return view('supervisor.thesisreview', compact("user", "student"));
    }

    public function store_review(Request $request)
    {
        $this->validate($request, [
        'comment' => 'required',
        'advice' => 'required',
        'grade' => 'required|numeric',
        ]);

        $student = Student::find($request->input('student_id'));
        $thesis = $student->thesis;
        $thesis->comment = $request->input('comment');
        if ($request->input('advice') == "") {
            $thesis->advice = "";
        }
        if ($request->input('comment') == "") {
            $thesis->advice = "";
        }   
        $thesis->advice = $request->input('advice');
        if ($request->input('grade') != "") {
            $thesis->grade = $request->input('grade');
        }
        $thesis->save();
        return redirect()->back()->withInput()->withErrors('提交成功！');
    }

    public function down_grade($student_id)
    {
        $student = Student::find($student_id);
        $file = public_path('cjd_template.docx');
        $templateProcessor = new TemplateProcessor($file);
        $templateProcessor->setValue('major', $student->major);
        $templateProcessor->setValue('enroll_time', "20" . substr($student->user->username, 0,2));
        $templateProcessor->setValue('student_id', $student->user->username);
        $templateProcessor->setValue('student_name', $student->user->name);
        $templateProcessor->setValue('class', $student->class);
        //$templateProcessor->setValue('supervisor', $user->name);
        //$templateProcessor->setValue('jobtitle', $user->supervisor->title);
        $title = "学生暂未选题";
        $current = $student->title()->where('current', '>', 0)->first();
        if ($current) {
            $title = $current->title;
        }
        $templateProcessor->setValue('title', $title);


        $supervise_comment = $student->supervise_comment;
        $supervise_content = "";
        $supervise_grade = "";
        if ($supervise_comment) {
            $supervise_content = $supervise_comment->content;
            $supervise_grade = $supervise_comment->grade;
        }
        $templateProcessor->setValue('supervise_comment', $supervise_content);
        $templateProcessor->setValue('supervise_grade', $supervise_grade);
        $supervisor = $student->supervisors()->first();
        if ($supervisor != null) {
            $templateProcessor->setValue('supervisor', $supervisor->user->name);
            $templateProcessor->setImageValue('supervisor_image', array("path"=>public_path('signs/' . $supervisor->user->name . '.JPG'),
                "height"=>25));
            $templateProcessor->setValue('jobtitle', $supervisor->title);
        } else {
            $templateProcessor->setValue('supervisor', "");
            $templateProcessor->setValue('supervisor_image', "");
            $templateProcessor->setValue('jobtitle', "");
        }        


        $review_comment = $student->review_comment;
        $review_content = "";
        $review_grade = "";
        if ($review_comment) {
            $review_content = $review_comment->content;
            $review_grade = $review_comment->grade;
        }
        $templateProcessor->setValue('review_comment', $review_content);
        $templateProcessor->setValue('review_grade', $review_grade);
        $reviewer = $student->reviewer()->first();
        if ($reviewer != null) {
            $templateProcessor->setImageValue('reviewer', array("path"=>public_path('signs/' . $reviewer->user->name . '.JPG'),
                "height"=>25));
        } else {
            $templateProcessor->setValue('reviewer', "");
        }

        $defense_comment = $student->defense_comment;
        $defense_content = "";
        $defense_grade = "";
        if ($defense_comment) {
            $defense_content = $defense_comment->content;
            $defense_grade = $defense_comment->grade;
        }
        $templateProcessor->setValue('defense_comment', $defense_content);
        $templateProcessor->setValue('defense_grade', $defense_grade);
        $defense_teacher = $student->defense_teacher()->first();
        if ($defense_teacher != null) {
            $templateProcessor->setImageValue('defense_teacher', array("path"=>public_path('signs/' . $defense_teacher->user->name . '.JPG'),
                "height"=>25));
        } else {
            $templateProcessor->setValue('defense_teacher', "");
        }        

        if ($supervise_grade == "" || $review_grade == "" || $defense_grade == "" ) {
            $templateProcessor->setValue('total_grade', "");
            $templateProcessor->setValue('rank', "");
        } else {
            $total_grade = $supervise_grade * 0.3 + $review_grade * 0.3 + $defense_grade * 0.4;
            $templateProcessor->setValue('total_grade', $total_grade);
            $rank = "不及格";
            if ($total_grade >= 90) {
                $rank = "优秀";
            } else if ($total_grade >= 80) {
                $rank = "良好";
            } else if ($total_grade >= 70) {
                $rank = "中等";
            } else if ($total_grade >= 60) {
                $rank = "及格";
            }
            $templateProcessor->setValue('rank', $rank);
        }
        $templateProcessor->saveAs(public_path('cjd/cjd_' . $student->user->username . '.docx'));
        return response()->download(public_path('cjd/cjd_' . $student->user->username . '.docx'));
    }


    public function down_dbzgscb($student_id)
    {
        $student = Student::find($student_id);
        $file = public_path('dbzg_template.docx');
        $templateProcessor = new TemplateProcessor($file);
        $templateProcessor->setValue('major', $student->major);
        $templateProcessor->setValue('student_id', $student->user->username);
        $templateProcessor->setValue('student_name', $student->user->name);
        $templateProcessor->setValue('class', $student->class);
        //$templateProcessor->setValue('supervisor', $user->name);
        //$templateProcessor->setValue('jobtitle', $user->supervisor->title);
        $title = "学生暂未选题";
        $current = $student->title()->where('current', '>', 0)->first();
        if ($current) {
            $title = $current->title;
        }
        $templateProcessor->setValue('title', $title);


        $supervise_comment = $student->supervise_comment;
        $supervise_content = "";
        $supervise_grade = "";
        if ($supervise_comment) {
            $supervise_content = $supervise_comment->content;
            $supervise_grade = $supervise_comment->grade;
        }
        $templateProcessor->setValue('supervise_comment', $supervise_content);
        $templateProcessor->setValue('supervise_grade', $supervise_grade);
        $supervisor = $student->supervisors()->first();
        if ($supervisor != null) {
            $templateProcessor->setImageValue('supervisor_image', array("path"=>public_path('signs/' . $supervisor->user->name . '.JPG'),
                "height"=>25));
        } else {
            $templateProcessor->setValue('supervisor_image', "");
        }        

        $templateProcessor->saveAs(public_path('dbzgscb/dbzgscb_' . $student->user->username . '.docx'));
        return response()->download(public_path('dbzgscb/dbzgscb_' . $student->user->username . '.docx'));
    }


    public function down_pyrpsb($student_id)
    {
        $student = Student::find($student_id);
        $file = public_path('pyrpsb_template.docx');
        $templateProcessor = new TemplateProcessor($file);
        $templateProcessor->setValue('major', $student->major);
        $templateProcessor->setValue('student_id', $student->user->username);
        $templateProcessor->setValue('student_name', $student->user->name);
        $templateProcessor->setValue('reviewer', $student->reviewer()->first()->user->name);
        $templateProcessor->setValue('jobtitle', $student->reviewer()->first()->title);
        $title = "学生暂未选题";
        $current = $student->title()->where('current', '>', 0)->first();
        if ($current) {
            $title = $current->title;
        }
        $templateProcessor->setValue('title', $title);


       


        $review_comment = $student->review_comment;
        $review_content = "";
        $review_grade = "";
        if ($review_comment) {
            $review_content = $review_comment->content;
            $review_grade = $review_comment->grade;
        }
        $templateProcessor->setValue('review_comment', $review_content);
        $templateProcessor->setValue('review_grade', $review_grade);
        $reviewer = $student->reviewer()->first();
        if ($reviewer != null) {
            $templateProcessor->setImageValue('reviewer_image', array("path"=>public_path('signs/' . $reviewer->user->name . '.JPG'),
                "height"=>25));
        } else {
            $templateProcessor->setValue('reviewer_image', "");
        }

        if ($review_grade >= 80) {
            for ($i = 1; $i < 15; $i++) {
                $r = rand(0, 100) * $review_grade;
                if ($r > 3500) {
                    $templateProcessor->setValue('h' . $i, "☑");
                    $templateProcessor->setValue('j' . $i, "□");
                } else {
                    $templateProcessor->setValue('h' . $i, "□");
                    $templateProcessor->setValue('j' . $i, "☑");
                }
                $templateProcessor->setValue('y' . $i, "□");
                $templateProcessor->setValue('c' . $i, "□");
            }
        } else if ($review_grade > 60) {
            for ($i = 1; $i < 15; $i++) {
                $r = rand(0, 100) * $review_grade;
                if ($r > 3500) {
                    $templateProcessor->setValue('j' . $i, "☑");
                    $templateProcessor->setValue('y' . $i, "□");
                } {
                    $templateProcessor->setValue('j' . $i, "□");
                    $templateProcessor->setValue('y' . $i, "☑");
                }
                $templateProcessor->setValue('h' . $i, "□");
                $templateProcessor->setValue('c' . $i, "□");
            }
        }

        if ($review_grade >= 90) {
            $templateProcessor->setValue('origin1', "☑");
            $templateProcessor->setValue('origin2', "□");
        } else {
            $templateProcessor->setValue('origin2', "☑");
            $templateProcessor->setValue('origin1', "□");
        }
        $templateProcessor->setValue('origin3', "□");
        $templateProcessor->setValue('origin4', "□");

        
        $templateProcessor->saveAs(public_path('pyrpsb/pyrpsb_' . $student->user->username . '.docx'));
        return response()->download(public_path('pyrpsb/pyrpsb_' . $student->user->username . '.docx'));
    }

}
